package com.flowable.flowabledemo.demos.web;

import org.flowable.engine.ProcessEngine;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.repository.ProcessDefinitionQuery;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * 流程控制
 */
@RestController
@RequestMapping("/flowable")
public class FlowableController {

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private RepositoryService repositoryService;


    /**
     * 发起流程审批(流程定义key)
     *
     * @return
     */
    @GetMapping("/startProcessInstanceByKey")
    public void startProcessInstanceByKey(@RequestParam String key) {
        //"holidayRequest"
        ProcessInstance holidayInstance = runtimeService.startProcessInstanceByKey(key);
        System.out.println(holidayInstance.toString());
    }

    /**
     * 部署流程定义
     * 有bug 不能生成流程定义
     * @param key
     * @return
     */
    @PostMapping("/createDeployment")
    @Deprecated
    public void createDeployment(@RequestParam String key, @RequestParam("file") MultipartFile file) throws IOException {
        Deployment deploy = repositoryService.createDeployment()
                .addInputStream(key, file.getInputStream())
                .deploy();
        System.out.println(deploy.toString());
    }

    /**
     * 本地xml 部署流程定义
     * @return
     */
    @PostMapping("/createResourceDeployment")
    public void createResourceDeployment() {
        Deployment deployment = repositoryService.createDeployment()
                .addClasspathResource("holiday-request.bpmn20.xml")
                .deploy();
        System.out.println(deployment.toString());

    }

    /**
     * 查看流程定义列表
     *
     * @param id 565fc96a-0538-11ef-b5ad-4c5f70aad13d
     * @return
     */
    @GetMapping("/getDeploymentList")
    public void getDeploymentList(@RequestParam String id) {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(id).singleResult();
        System.out.println(processDefinition);
    }

}
